﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Win64MKC;

namespace 千牛批量开票助手
{
    public partial class FrmTest : Form
    {
        // 浏览器设置
        private CefSettings cefSettings = new CefSettings
        {
            Locale = "zh-CN",
            AcceptLanguageList = "zh-CN",
            MultiThreadedMessageLoop = true
        };

        public FrmTest()
        {
            InitializeComponent();
            Cef.Initialize(cefSettings);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            cmWeb.Load("https://einvoice.taobao.com/#/online/invoice/apply");
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            cmWeb.Refresh();
            cmWeb.SetZoomLevel(-1);
        }

        private void txtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox txt = sender as TextBox;
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrWhiteSpace(txt.Text)) cmWeb.Load(txt.Text);
            }
        }

        private void cmWeb_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            this.Invoke(new Action(() => {
                if (e.IsLoading)
                {
                    if (txtUrl.Text.ToLower().Contains("login.taobao.com"))
                    {
                        //// 自动跳转发票列表
                        //cmWeb.Load("https://einvoice.taobao.com/#/online/invoice/apply");
                    }
                } else
                {
                    cmWeb.SetZoomLevel(-1);
                }

            }));
        }

        private void cmWeb_TitleChanged(object sender, TitleChangedEventArgs e)
        {
            this.Invoke(new Action(() => {
                txtUrl.Text = cmWeb.Address;

                /** 注入 js 脚本 **/
                if (txtUrl.Text.ToLower().Contains("login.taobao.com"))
                {
                    // 注入 JS 输入用户名和密码
                    StringBuilder js = new StringBuilder();
                    js.Append("const InputLoginInfo = async (usr, pwd) => {");
                    js.Append("    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));");
                    js.Append("    document.getElementById('fm-login-id').value = usr;");
                    js.Append("    document.getElementById('fm-login-password').value = pwd;");
                    js.Append("    await sleep(200);");
                    js.Append("    document.getElementsByClassName('password-login')[0].click();");
                    js.Append("};");
                    cmWeb.ExecuteScriptAsync(js.ToString());
                } 
                else if (txtUrl.Text.ToLower().Contains("einvoice.taobao.com"))
                {
                    // 注入 JS 输入订单编号
                    StringBuilder js = new StringBuilder();
                    js.Append("const InputOrderNum = (num) => {");
                    js.Append("    let ctrls = document.getElementsByClassName('invoice-conditions-label');");
                    js.Append("    for (i = 0; i < ctrls.length; i++) {");
                    js.Append("        if (ctrls[i].innerHTML == '订单编号') {");
                    js.Append("            let input = ctrls[i].parentNode.getElementsByTagName('input')[0];");
                    js.Append("            input.value = num;");
                    js.Append("            ");
                    js.Append("            let event = new Event('input', { bubbles: true });");
                    js.Append("            let tracker = input._valueTracker;");
                    js.Append("            if (tracker) tracker.setValue('');");
                    js.Append("            input.dispatchEvent(event);");
                    js.Append("            ");
                    js.Append("            document.getElementsByClassName('condition_btn-HfaSh')[0].getElementsByTagName('button')[0].click();");
                    js.Append("            return;");
                    js.Append("        }");
                    js.Append("    }");
                    js.Append("};");
                    js.Append("");
                    js.Append("const GetSearchCount = () => {");
                    js.Append("    let content = document.getElementsByClassName('invoice-search-table-middle')[0].getElementsByClassName('left-label')[0].innerHTML;");
                    js.Append(@"    return parseInt(/\d+/g.exec(content)[0]);");
                    js.Append("};");
                    js.Append("const ClickAllow = async () => {");
                    js.Append("    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));");
                    js.Append("");
                    js.Append("    let rows = document.getElementsByClassName('invoice-search-table-middle')[0].parentNode.parentNode.getElementsByClassName('ant-table-content')[0].getElementsByClassName('ant-table-body')[0].getElementsByClassName('ant-table-row-level-0');");
                    js.Append("    let ctrls = rows[0].getElementsByTagName('td')[9].getElementsByTagName('a');");
                    js.Append("    let flag = -1;");
                    js.Append("    for (i = 0; i < ctrls.length; i++) {");
                    js.Append("        if(ctrls[i].innerHTML == '同意') {");
                    js.Append("            flag = i;");
                    js.Append("            break;");
                    js.Append("        }");
                    js.Append("    }");
                    js.Append("    ctrls[flag].click();");
                    js.Append("");
                    // js.Append("    // 0.5 秒后在弹出的对话框里选择[在[待录入列表]中手动上传发票]类型");
                    js.Append("    await sleep(500);");
                    js.Append("    document.getElementsByClassName('next-dialog')[0].getElementsByTagName('label')[1].click();");
                    js.Append("    await sleep(1000);");
                    // js.Append("    // document.getElementsByClassName('next-dialog')[0].getElementsByTagName('button')[0].click()"); // 确定
                    js.Append("    document.getElementsByClassName('next-dialog')[0].getElementsByTagName('button')[1].click();"); // 取消
                    js.Append("};");

                    js.Append("const ClickInput = async (count) => {");
                    js.Append("    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));");
                    js.Append("");
                    js.Append("    let rows = document.getElementsByClassName('invoice-search-table-middle')[0].parentNode.parentNode.getElementsByClassName('ant-table-content')[0].getElementsByClassName('ant-table-body')[0].getElementsByClassName('ant-table-row-level-0');");
                    js.Append("    let ctrls = rows[0].getElementsByTagName('td')[8].getElementsByTagName('a');");
                    js.Append("    let flag = -1;");
                    js.Append("    for (i = 0; i < ctrls.length; i++) {");
                    js.Append("        if(ctrls[i].innerHTML == '录入发票') {");
                    js.Append("            flag = i;");
                    js.Append("            break;");
                    js.Append("        }");
                    js.Append("    }");
                    js.Append("    ctrls[flag].click();");
                    js.Append("");
                    // js.Append("    // 0.5 秒后在弹出的对话框里插入发票");
                    js.Append("    await sleep(500);");
                    js.Append("");
                    // js.Append("    // 根据发票数量创建对应的输入框");
                    js.Append("    for (i = 0; i < count-1; i++) {");
                    js.Append("        document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=\"bodyContent\"]')[0].scrollTo(0, 50000);");
                    js.Append("        await sleep(500);");
                    js.Append("        document.getElementsByClassName('next-dialog')[0].querySelectorAll('span[class*=\"handleBtn\"]')[0].click();");
                    js.Append("        await sleep(500);");
                    js.Append("    }");
                    js.Append("};");
                    js.Append("const UploadClick = async (i) => {");
                    js.Append("    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));");
                    js.Append("    ");
                    js.Append("    document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=\"bodyContent\"]')[0].querySelectorAll('div[class*=\"invoiceFormBlock\"')[i].scrollIntoView({ block: \"start\" });");
                    js.Append("    await sleep(500);");
                    js.Append("    document.getElementsByClassName('next-dialog')[0].querySelectorAll('div[class*=\"bodyContent\"]')[0].querySelectorAll('div[class*=\"invoiceFormBlock\"')[i].getElementsByTagName('button')[0].click();");
                    js.Append("    await sleep(500);");
                    js.Append("};");
                    cmWeb.ExecuteScriptAsync(js.ToString());
                }
            }));
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            if (txtUrl.Text.ToLower().Contains("login.taobao.com"))
            {
                // 注入 JS 输入用户名和密码
                cmWeb.ExecuteScriptAsync($"InputLoginInfo('{textBox1.Text}', '{textBox2.Text}');");
                //Task task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait();

                //// 自动跳转发票列表
                //while (cmWeb.GetBrowser().IsLoading) { task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait(); }
                //cmWeb.Load("https://einvoice.taobao.com/#/online/invoice/apply");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtUrl.Text.ToLower().Contains("online/invoice/apply"))
            {
                // 注入 JS 输入订单编号
                cmWeb.ExecuteScriptAsync($"InputOrderNum('{textBox3.Text}');");
                Task task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait();

                Console.WriteLine(cmWeb.EvaluateScriptAsync($"GetSearchCount()").Result.Result.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (txtUrl.Text.ToLower().Contains("online/invoice/apply"))
            {
                // 注入 JS 点击[同意]
                cmWeb.ExecuteScriptAsync($"InputOrderNum('{textBox3.Text}');");
                Task task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait();

                if (int.Parse(cmWeb.EvaluateScriptAsync($"GetSearchCount()").Result.Result.ToString()) > 0)
                {
                    cmWeb.ExecuteScriptAsync($"ClickAllow()");
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (txtUrl.Text.ToLower().Contains("online/invoice/pending"))
            {
                // 注入 JS 输入订单编号
                cmWeb.ExecuteScriptAsync($"InputOrderNum('{textBox4.Text}');");
                Task task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait();

                Console.WriteLine(cmWeb.EvaluateScriptAsync($"GetSearchCount()").Result.Result.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (txtUrl.Text.ToLower().Contains("online/invoice/pending"))
            {
                // 注入 JS 点击[录入发票]
                cmWeb.ExecuteScriptAsync($"InputOrderNum('{textBox3.Text}');");
                Task task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait();

                if (int.Parse(cmWeb.EvaluateScriptAsync($"GetSearchCount()").Result.Result.ToString()) > 0)
                {
                    cmWeb.ExecuteScriptAsync($"ClickInput({textBox5.Text})");
                }
            }
        }

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        private void button5_Click(object sender, EventArgs e)
        {
            if (txtUrl.Text.ToLower().Contains("online/invoice/pending"))
            {
                // 注入 JS 点击[上传PDF/OFD]
                cmWeb.GetBrowser().GetHost().SetFocus(true);
                cmWeb.ExecuteScriptAsync($"UploadClick('{textBox6.Text}');");
                Task task = Task.Run(async delegate { await Task.Delay(1000); }); task.Wait();

                int timeout = 0;
                IntPtr dialogHwnd = IntPtr.Zero;
                while (timeout < 10)
                {
                    dialogHwnd = FindWindow("#32770", "打开");
                    if (dialogHwnd != IntPtr.Zero) { break; } else { task = Task.Run(async delegate { await Task.Delay(500); }); task.Wait(); }
                }

                // 获取窗体
                //FindWindowEx(dialogHwnd, IntPtr.Zero, null, );
                Console.WriteLine(FindWindow("#32770", "打开").ToString());
            }
        }

        
    }
}
